<template>
  <div>
    <div class="top-container" :style="{ backgroundImage: 'url(' + checkInBackImg + ')' }">
      <rtheader :title="'签到'" :ischeckin='true'></rtheader>
      <div class="rule" @click="rules"><span>签到规则</span></div>
      <div class="top">
<!--        <div class="flex1 icon-num a-c">-->
<!--          <span class="yl-jf-b lvb-icon "></span>-->
<!--          <span >{{obj.totalCoin}}</span>-->
<!--        </div>-->
<!--        <div class="text-center a-c">-->
<!--          <div class="outer a-c">-->
<!--            <div class="inner-check a-c">-->
<!--              <div>-->
<!--                <span class="check-number">+{{obj.addCoin||0}}</span>-->
<!--                <span class="check-text">签到成功</span>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
        <div class="check-btn">
          <span><b style="font-size: 0.52rem">+{{obj.addCoin||0}}</b><br/>今日签到成功</span>
        </div>
<!--        <div class="flex1 checkinrule v-c " >-->
<!--          <span class="yl-ji-how lvb-icon" @click="showRepairExplain"></span>-->
<!--          <span @click="getPopShow"> 补签</span>-->

<!--        </div>-->
<!--        <p class="continue">已连续签到{{obj.continuityDays||0}}天</p>-->
      </div>
      <div class="continue">
        <span>连续签到{{obj.continuityDays||0}}天</span>
      </div>

    </div>

    <div class="check-record">
      <div class="check-record-item">
        <span>我的绿币：</span>
        <em style="color: #FB685B;font-size: 0.4rem;font-style: normal">{{obj.totalCoin}}</em>
      </div>
      <div class="check-record-item check-record-repair" >
        <img src="../../assets/icon-help2.png" @click="showRepairExplain"/>
        <span @click="getPopShow">补签</span>
      </div>
    </div>

    <div class="mask" v-show="isLottery"></div>
    <div id="top" class="lottery-pop" :class="{ bg2: isBegin && !isWin}" v-show="isLottery">
      <img class="lottery-title" src="https://youlingqinius.wonderlandnet.cn/youlin-lottery-title.png" />
      <div class="lottery-main">
        <div v-if="prizePicture" style="width:100%;height:1.15rem;margin: 0 auto;">
          <img style="height:100%;max-width: 3rem;" :src="prizePicture">
        </div>
        <div v-if="prizePicture" style="height:.6rem;line-height: .6rem;">{{prizeName}}</div>
        <div v-else>{{prizeName}}</div>
      </div>
      <canvas
        id="c1" class="canvas"
        @touchmove="touchmove"
        @touchstart="touchstart"
        @touchend="touchend"
        
        v-if="!isScratch"
      ></canvas>
      <div class="lottery-btn" :style="{top:(!isScratch?'-1.5rem':'.4rem')}" @click="doDraw" v-show="!isBegin || isWin">{{btnText}}</div>
<!--      <img id="imgs" class="lottery-mask" src="https://youlingqinius.wonderlandnet.cn/youlin-lottery-mask.jpg" style="display: none" />-->
<!--      <img id="imgs" class="lottery-mask" src="../../assets/lottery/lottery-mask.jpg" style="display: none" />-->
    </div>
    <img class="close-btn" src="https://youlingqinius.wonderlandnet.cn/youlin-icon-close.png" v-show="isLottery && !isWin" @click="closePop" />

    <calendar :obj="obj.monthData" @tips="openTips" v-if="obj.monthData" :repairSignIn="repairSignIn" style="width: 6.9rem;background: #fff;border-radius: 0.1rem;margin:0.7rem 0.3rem 0"></calendar>
    <rotatepop  :ispopshow="ispopshow" @ispopshow="confirmpop" :ischeckin="true" :extracoin="this.obj.monthData.extra.extraCoin" v-if="this.obj.monthData"></rotatepop>
    <deletepopup :poptext="poptext" @candelete="repairSignIn" @cancledelete="showPop=!showPop" :isshowdeletepopup="showPop" @deleteshow="deleteshow" :type="showType" :showcancle="showcancle"></deletepopup>
  </div>
</template>

<script>
import calendar from 'components/calendar/calendar'
import rotatepop from "src/components/rotate/rotatepop.vue";
import api from "src/api/index";
import { MessageBox } from 'mint-ui';
import rtheader from "src/components/rotate/rt-header.vue";
import deletepopup from "src/components/deletepopup.vue";
import Vue from 'vue';
export default {
  name:"checkin",
  inject:['reload'],
  components: {
    calendar,
    rotatepop,
    rtheader,
    deletepopup
  },
  data() {
    return {
      obj: {},
      ispopshow:false,
      poptext:"",
      showPop:false,
      showcancle:true,
      showType:3,
      checkInBackImg:"",
      backgroundType:this.$route.query.backgroundType,
      signBackground:this.$route.query.signBackground,
      isSign: this.$route.query.isSign,
      isLottery: false,
      btnText: '',
      drawId: '',
      isBegin: false,
      prizeInfo:  {},
      prizeName: '',
      prizePicture: '',
      isWin: false,

      c1: "", //画布
      ctx: "", //画笔
      img: "",
      ismousedown: false, //标志用户是否按下鼠标或开始触摸
      fontem: "", // 获取html字体大小
      isScratch: false, // 是否刮过卡
    }
  },
  created() {
    // this.getCoinShopIndex()
    this.init()
  },
  mounted() {
    this.initCanvaskk();
  },
  methods: {
     getCoinShopIndex() {
      let p = new Promise((resolve, reject) => {
        api.getCoinShopIndex().then(res => {
          if (res.success) {
            this.signType = res.data.signType;
            this.isSign = res.data.signType;
            this.backgroundType = res.data.backgroundType;
            this.signBackground = res.data.signBackground;
            this.init()
            resolve("获取商城列表....");
          }
        });
      });
      return p;
    },
    // 画刮刮卡
    initCanvaskk() {
      this.fontem = parseInt(
        window.getComputedStyle(document.documentElement, null)["font-size"]
      ); //这是为了不同分辨率上配合@media自动调节刮的宽度
      this.c1 = document.getElementById("c1");
      this.ctx = this.c1.getContext("2d");
      // let img = document.getElementById('imgs')
      let img = new Image();
      // img.src = require('https://youlingqinius.wonderlandnet.cn/youlin-lottery-mask.jpg'); // 默认的背景图片
      img.src = require('../../assets/lottery/lottery-mask.jpg'); // 默认的背景图片
      this.img = img;
      let that = this;
      img.onload = function() {
        that.ctx.drawImage(img, 0, 0, that.c1.width, that.c1.height)
        that.ctx.globalCompositeOperation = 'destination-out' // 橡皮擦
      }
    },
    touchstart(e) {
      if (!this.isBegin) return;
      e.preventDefault();
      this.ismousedown = true;
    },
    // 操作刮卡
    touchend(e) {
      sessionStorage.setItem('isScratch',true)
      e.preventDefault();
      //得到canvas的全部数据
      let a = this.ctx.getImageData(0, 0, this.c1.width, this.c1.height);
      let j = 0;
      for (let i = 3; i < a.data.length; i += 4) {
        if (a.data[i] == 0) j++;
      }
      //当被刮开的区域等于一半时，则可以开始处理结果
      if (j >= a.data.length / 8) {
        this.isScratch = true;
        let prizeType = this.prizeInfo.prizeType;
        if (prizeType == 1 || prizeType == 3) {
          this.btnText = '填写地址';
          this.isWin = true;
        } else if (prizeType == 2 || prizeType == 4) {
          this.btnText = '领取奖励';
          this.isWin = true;
        }
      } else {
        let that = this;
        setTimeout(function(){
          that.ctx.clearRect(0, 0, that.c1.width,that.c1.height);
          that.ctx.globalCompositeOperation = 'source-over';
          that.ctx.drawImage(that.img, 0, 0, that.c1.width, that.c1.height);
          that.ctx.globalCompositeOperation = 'destination-out';
          that.isScratch = false;
        }, 2000);
      }
      this.ismousedown = false;
    },
    touchmove(e) {
      e.preventDefault();
      if (this.ismousedown) {
        if (e.changedTouches) {
          e = e.changedTouches[e.changedTouches.length - 1];
        }
        let topY = document.getElementById("top").offsetTop;
        let oX = this.c1.offsetLeft,
            oY = this.c1.offsetTop + topY,
            x = (e.clientX + document.body.scrollLeft || e.pageX) - oX || 0,
            y = (e.clientY + document.body.scrollTop || e.pageY) - oY || 0;
        //画360度的弧线，就是一个圆，因为设置了ctx.globalCompositeOperation = 'destination-out';
        this.ctx.beginPath();
        this.ctx.arc(x, y, this.fontem , 0, Math.PI * 2, true); // 调整画笔的大小
        //下面3行代码是为了修复部分手机浏览器不支持destination-out
        // this.c1.style.display = 'none';
        // this.c1.offsetHeight;
        // this.c1.style.display = 'inherit';
        this.ctx.fill();
      }
    },

    init(){
      api.getCheckData().then(res => {
        if(res.success){
          this.$util.saveFootPrint({actType:16,typeValue:""});//用户轨迹
          this.obj = res.data
          this.getCheckInBg();
        }
      })

      if (this.isSign != 1) {
        api.canDraw().then(res => { // 是否有可用抽奖
          if(res.success){
            this.isLottery = true;
            this.btnText = '消耗' + res.cost + '绿币刮奖';
            this.drawId = res.drawId;
          }
        })
      }
    },
    doDraw(){ // 抽奖
      const params ={drawId:this.drawId}
      if (!this.isBegin) {
        api.doDraw(params).then(res => {
          if(res.success){
            this.isBegin = true;
            this.prizeInfo = res.result;
            this.prizeName = res.result.prizeName;
            this.prizePicture = res.result.prizePicture;
          }else{
            this.isBegin = true;
            // this.isScratch = true;
            this.prizeName = res.msg;
          }
        })
      } else {
        if (this.isWin) {
          let prizeType = this.prizeInfo.prizeType;
          if(prizeType==1){//快递实物
            this.$router.push({path:"/address",query:{tag:1,id:this.prizeInfo.recordId}});
          }else if(prizeType==2){//红包
            this.$router.push({path:"/submitresult",query:{tag:1,prizeName:this.prizeInfo.prizeName}});
          }else if(prizeType==3){//自取实物
            this.$router.push({path:"/shipaddress",query:{tag:0,id:this.prizeInfo.recordId,typeValue:this.prizeInfo.typeValue}});
          }else if(prizeType==4){//绿币
            this.$router.push({path:"/submitresult",query:{tag:2,prizeName:this.prizeInfo.prizeName}});
          }
        }
      }
    },
    closePop(){
      this.isLottery = false;
    },
    getCheckInBg(){//更改签到背景
      if(this.signBackground!=null){
        this.checkInBackImg = this.signBackground
      }else{
        switch (String(this.backgroundType)){
          case "1":
          this.checkInBackImg="https://youlingqinius.wonderlandnet.cn/jf-bg.png"
          break;
          case "2":
          this.checkInBackImg="https://youlingqinius.wonderlandnet.cn/checkin-snow.png"
          break;
          case "3":
          this.checkInBackImg="https://youlingqinius.wonderlandnet.cn/checkin-newyear.png"
          break;
          default:
          this.checkInBackImg="https://youlingqinius.wonderlandnet.cn/jf-bg.png"
          break;
        }
      }
    },
    rules() {
      this.$router.push({ path: '/activityrule', query: { tag: 4 } });
    },
    openTips() {
      this.ispopshow=true;
      // this.dialog(`连续签到至该天可额外获得${this.obj.monthData.extra.extraCoin}个绿币`)
    },
    confirmpop(){
      this.ispopshow=false;
    },
    parse(s) {
      return s != '' ? new Date(s).toLocaleDateString() : new Date().toLocaleDateString()
    },
    deleteshow(data){
        this.showPop=data;
    },
    getPopShow(){
      if(!this.obj.allowSign){
        this.$toast("今日已补签")
      }else{
        this.poptext="补签需消耗"+this.obj.repairUseCoin+"绿币，您最近的漏签日期为"+this.obj.repairDate+"，确定要补签吗？"
        this.showcancle = true;
        this.showType = 3
        this.showPop = true
      }
    },
    showRepairExplain(){
      this.poptext=this.obj.repairExplain
      this.showPop=true
      this.showcancle = false;
      this.showType=4
      //this.getPopShow()
    },
    repairSignIn(){
      if(this.showType==3){
        const params ={date:this.obj.repairDate}
        api.repairSignIn(params).then(res=>{
          this.showPop=false
          if(res.success){
            this.$toast("补签成功")
            this.reload()
          }else {
            this.$toast(res.msg)
          }
        })
      }else{
        this.showPop=false
      }
    }
  }
}

</script>

<style lang="less" scoped>
  * { touch-action: pan-y; }
  .top-container {
  width: 100%;
  height: 5.8rem;
  margin-top: -0.88rem;
  background-image: url('https://youlingqinius.wonderlandnet.cn/qian-bg.png');
  background-size: cover;
  background-repeat: no-repeat;
}
  .rule{
    width: 1.52rem;
    height: 0.56rem;
    background: rgba(0,0,0,0.2);
    border-top-left-radius: 0.56rem;
    border-bottom-left-radius: 0.56rem;
    color: #fff;
    font-size: 0.28rem;
    text-align: center;
    line-height: 0.58rem;
    position: relative;
    top: 1.12rem;
    left: 5.98rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }

.top {
  position: relative;
  //padding: 0 0.3rem;
  top: 1.22rem;
  //color: #fff;
  display: flex;
  justify-content: center;
  //font-size: 15px;
  //flex-wrap: wrap;
  .icon-num{
    font-size:0.36rem;
    font-family: PingFangSC-Medium, sans-serif;
    justify-content: flex-start;
  }
  .lvb-how{
    font-family: PingFangSC-Regular, sans-serif;
    font-size:0.3rem;
    text-align: right;
    justify-content: flex-end;
  }
}

//.check-box{
//  display: flex;
//  justify-content: center;
//  align-items: center;
//  margin-top: 1.8rem;
//}
.check-btn{
  width: 2.2rem;
  height: 2.2rem;
  background: url("https://youlingqinius.wonderlandnet.cn/youlin-check-bg.png");
  background-size: 100%;
  color: #FC6855;
  font-size: 0.24rem;
  text-align: center;
  line-height: 0.44rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

  .check-record{
    width: 6.9rem;
    height: 0.96rem;
    padding: 0 0.32rem;
    background: #fff;
    border-radius: 0.1rem;
    position: fixed;
    top: 5.3rem;
    left: 0.3rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #666;
    font-size: 0.28rem;
  }
  .check-record-item{
    display: flex;
    align-items: center;
  }
  .check-record-repair{
    justify-content: center;
    width: 1.24rem;
    height: 0.48rem;
    background: #FC6855;
    border-radius: 0.48rem;
    color: #fff;
    font-size: 0.24rem;
  }
  .check-record-item img{
    width: 0.28rem;
    height: 0.28rem;
    margin-right: 0.06rem;
  }
.lvb-icon{
  padding: 0.02rem 0.06rem 0 0;
}

.continue {
  position: relative;
  top: 1.68rem;
  width: 100%;
  //margin-top: 10px;
  color: #fff;
  font-size: 0.28rem;
  text-align: center;
}
.continue span{
  padding: 0.1rem 0.2rem;
  background: rgba(0,0,0,0.2);
  border-radius: 2rem;
}

.checkinrule{
  justify-content: flex-end;
}

.check-number {
  display: block;
  width: 100%;
  font-size: 22px;
  font-weight: 600;
}

.outer {
  width: 86px;
  height: 86px;
  border-radius: 50%;
  // background-color: #FC907D;
  background: (rgba(255, 255, 255, 0.1))
}

.inner-check {
  width: 76px;
  height: 76px;
  color: #F97165;
  border-radius: 50%;
  background-color: #fff;
}

.check-text {
  font-size: 13px;
}

.mint-msgbox-confirm {
  font-size: 0.32rem;
  color: #FB685B;
}

.mask{
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 5000;
}

.lottery-pop{
  width: 6rem;
  height: 7.7rem;
  background: url("https://youlingqinius.wonderlandnet.cn/youlin-lottery-bg.png");
  background-size: 6rem 7.7rem;
  position: fixed;
  top: 3.1rem;
  left: 0.75rem;
  z-index: 5000;
  text-align: center;
}

.bg2{
  width: 6rem;
  height: 6.4rem;
  background: url("https://youlingqinius.wonderlandnet.cn/youlin-lottery-bg2.png");
  background-size: 6rem 6.4rem;
}

.lottery-title{
  width: 4.96rem;
  height: 0.54rem;
  margin-top: 2.04rem;
}

.lottery-main{
  width: 4.45rem;
  height: 1.95rem;
  /*background: #000;*/
  margin: 0.9rem auto 0 auto;
  color: #666;
  font-size: 0.28rem;
  text-align: center;
  line-height: 1.95rem;
  position: relative;
}

.canvas{
  position: relative;
  top: -1.95rem;
  left: 0;
  width: 4.45rem;
  height: 1.95rem;
}

.lottery-btn{
  width: 3.8rem;
  height: 1.08rem;
  background: url("https://youlingqinius.wonderlandnet.cn/youlin-lottery-btn.png");
  background-size: 3.8rem 1.08rem;
  margin: 0 auto;
  position: relative;
  top: -1.5rem;
  color: #BF2120;
  font-size: 0.34rem;
  font-weight: 500;
  text-align: center;
  line-height: 0.98rem;
}

.lottery-mask{
  width: 4.45rem;
  height: 1.95rem;
}

.close-btn{
  width: 0.7rem;
  height: 0.7rem;
  position: fixed;
  top: 12.3rem;
  left: 3.4rem;
  z-index: 5000;
}
</style>
